﻿@{
    ViewData["Title"] = "Index";
    Layout = "_OridinaryPage";
}

@section Header{
    <link rel="stylesheet" href="~/js/plugins/bootstrap-table/bootstrap-table.css" />
    <link rel="stylesheet" href="~/js/plugins/jquery-treegrid/css/jquery.treegrid.css" />
}

<section>
    <!--<h2>
        <small></small>
    </h2>-->
    <ol class="breadcrumb breadcrumb-pd clear-mgb bg-transparent">
        <li><a href="#"><i class="fa fa-dashboard"></i> 系统管理</a></li>
        <li class="active">字典管理</li>
    </ol>
</section>
<!-- Main content -->
<section class="content-mini clear-pdt clear-pdb">
    <div class="row">
        <div class="col-xs-12">
            <div class="box clear-mgb clear-mgb clearBoxTopBorder clearShadow">
                <!--<div class="box-header">
                    <h3 class="box-title"></h3>
                </div>-->
                <!-- /.box-header -->
                <div class="box-body clear-pd">
                    <div id="toolbar" class="btn-group">
                        @if (BaseHelper.HasPermission(SysDictionaryBtn.AddSub))
                        {
                            <button id="btnAddSub" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加子节点
                            </button>
                        }
                        @if (BaseHelper.HasPermission(SysDictionaryBtn.AddSibling))
                        {
                            <button id="btnAddSibling" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加同级节点
                            </button>
                        }
                        @if (BaseHelper.HasPermission(SysDictionaryBtn.Edit))
                        {
                            <button id="btnEdit" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
                            </button>
                        }
                        @if (BaseHelper.HasPermission(SysDictionaryBtn.Delete))
                        {
                            <button id="btnDelete" type="button" class="btn btn-default" data-toggle="modal">
                                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
                            </button>
                        }
                    </div>
                    <table id="dataInfos" class="table table-bordered table-hover"></table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<!-- /.content -->
<!-- addEditModal---start -->
<div id="addEditModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="addEditModal">
    <div class="modal-dialog modal-md" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">添加字典</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="addEditForm">
                    <div class="form-group">
                        <label for="addEditDictCode" class="col-sm-2 control-label">字典编码</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditDictCode" name="DictCode" placeholder="字典编码" maxlength="50">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditDictName" class="col-sm-2 control-label">字典名称</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditDictName" name="DictName" placeholder="字典名称" maxlength="50">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="addEditDictValue" class="col-sm-2 control-label">字典值</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditDictValue" name="DictValue" placeholder="字典值" maxlength="50">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditIsActive" class="col-sm-2 control-label">是否启用</label>
                        <div class="col-sm-9">
                            <select class="form-control" id="addEditIsActive" name="IsActive">
                                <option value="1">启用</option>
                                <option value="0">不启用</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditParentCode" class="col-sm-2 control-label">父级编码</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditParentCode" name="ParentCode" placeholder="父级编码" readonly="readonly">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="addEditRemarks" class="col-sm-2 control-label">备注</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control clear" id="addEditRemarks" name="Remarks" placeholder="备注" value="请勿修改" maxlength="200">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="btnAddEditSubmit" class="btn btn-primary">提交</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $("#btnAddEditSubmit").click(function () {
        var dictCode = $("#addEditDictCode").val();
        var dictName = $("#addEditDictName").val();
        var remarks = $("#addEditRemarks").val();
        if (IsNullOrEmpty(dictCode)) {
            alert("请输入字典编码！");
            $("#addEditDictCode").focus();
            return;
        }
        if (IsNullOrEmpty(dictName)) {
            alert("请输入字典名称！");
            $("#addEditDictName").focus();
            return;
        }
        if (IsNullOrEmpty(remarks)) {
            alert("请输入备注！");
            $("#addEditRemarks").focus();
            return;
        }
        IndexBtnDisabled();
        $.ajax({
            type: "post",
            url: $("#addEditDictCode").attr("readonly") == "readonly" ? "/Sys/Sys_Dictionary/Edit" : "/Sys/Sys_Dictionary/Add",
            data: $("#addEditForm").serialize(),
            dataType: "json",
            success: function (data) {
                if (data.Success) {
                    alert(data.Message);
                    $("#addEditModal").modal('hide');
                    $("button[name='refresh']").click();
                } else {
                    alert(data.Message);
                }
                IndexBtnEnabled();
            },
            error: function (err) { }
        });
    });
</script>
<!-- addEditModal---end -->

@section Scripts{
    <script src="~/js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
    <script src="~/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
    <script src="~/js/plugins/bootstrap-table/extensions/treegrid/bootstrap-table-treegrid.js"></script>
    <script src="~/js/plugins/jquery-treegrid/js/jquery.treegrid.js"></script>
    <script type="text/javascript">
        $(function () {
            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();
        });

        var $table = $('#dataInfos');
        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $table.bootstrapTable({
                    url: '/Sys/Sys_Dictionary/GetExtendList',
                    method: 'get',                      //请求方式（*）
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: false,                  //是否显示分页（*）
                    sidePagination: 'server',
                    search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                    searchOnEnterKey: true,
                    strictSearch: true,
                    queryParams: function (params) {
                        var temp = {   //这里键的名字和控制器的变量名必须一致，如有变动此处和控制器要一起改
                            //rowsPerPage: params.limit, //每页数据行数
                            //offsetRows: params.limit,  //已偏移行数
                            search: $("div.search input").val()
                        };
                        return temp;
                    },//传递参数（*）
                    showRefresh: true,                  //是否显示刷新按钮
                    showColumns: false,                 //是否显示所有的列
                    showToggle: false,                  //是否显示详细视图和列表视图的切换按钮
                    minimumCountColumns: 2,             //最少允许的列数
                    clickToSelect: false,               //是否启用点击选中行
                    //height: 811,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "DictCode",                 //每一行的唯一标识，一般为主键列
                    idField: 'DictCode',
                    parentIdField: 'VirtualParentCode',
                    treeShowField: 'DictName',
                    showToggle: false,                  //是否显示详细视图和列表视图的切换按钮
                    cardView: false,                    //是否显示详细视图
                    detailView: false,                  //是否显示父子表
                    columns: [
                        {
                            checkbox: true
                        }, {
                            field: 'DictName',
                            title: '字典名称'
                        }, {
                            field: 'DictCode',
                            title: '字典编码'
                        }, {
                            field: 'ParentCode',
                            title: '父级编码'
                        }, {
                            field: 'DictValue',
                            title: '字典值',
                        }, {
                            field: 'CreateDate',
                            title: '创建时间',
                            formatter: function (value, row, index) {
                                return getFormatDate(value);
                            }
                        }, {
                            field: 'Remarks',
                            title: '备注'
                        }, {
                            field: 'DictCode',
                            title: '操作',
                            formatter: 'operateFormatter'
                        }
                    ],
                    onLoadSuccess: function (data) {
                        $table.treegrid({
                            initialState: 'collapsed',//收缩
                            treeColumn: 1,//指明第几列数据改为树形
                            expanderExpandedClass: 'glyphicon glyphicon-triangle-bottom',
                            expanderCollapsedClass: 'glyphicon glyphicon-triangle-right',
                            onChange: function () {
                                $table.bootstrapTable('resetWidth');
                            }
                        });
                    }
                });
            };
            return oTableInit;
        };

        //格式化操作列的内容
        function operateFormatter(value, row, index) {
            var array = [];
            @if (BaseHelper.HasPermission(SysDictionaryBtn.Edit))
            {
                @:row._parent = ""; row._nodes = "";
                @:array.push("<a onclick='showEditModal(" + JSON.stringify(row) + ")' class='operateLink'><i class='fa fa-pencil-square-o' ></i>&nbsp;编辑</a>");
            }
            return array.join('');
        }

        $("#btnAddSub").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择父节点！");
                return;
            }
            if (selections.length > 1) {
                alert("只能选择一个父节点！");
                return;
            }
            $(".clear").val('');
            $("#addEditModal .modal-title").text("添加字典");
            $("#addEditDictCode").removeAttr("readonly");
            $("#addEditParentCode").val(selections[0].DictCode);
            $("#addEditIsActive").val('1');
            $("#addEditRemarks").val('请勿修改');
            $("#addEditModal").modal('show');
        });

        $("#btnAddSibling").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择节点！");
                return;
            }
            if (selections.length > 1) {
                alert("只能选择一个节点！");
                return;
            }
            $(".clear").val('');
            $("#addEditModal .modal-title").text("添加字典");
            $("#addEditDictCode").removeAttr("readonly");
            $("#addEditParentCode").val(selections[0].ParentCode);
            $("#addEditIsActive").val('1');
            $("#addEditRemarks").val('请勿修改');
            $("#addEditModal").modal('show');
        });

        $("#btnEdit").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择要修改的节点！");
                return;
            }
            if (selections.length > 1) {
                alert("只能选择一个要修改的节点！");
                return;
            }
            showEditModal(selections[0]);
        });

        function showEditModal(row) {
            if (IsNullOrEmpty(row.DictCode)) {
                alert("数据异常，请联系管理员！");
                return;
            }
            $("#addEditModal .modal-title").text("编辑字典");
            $("#addEditDictCode").attr("readonly", "readonly");
            $("#addEditDictCode").val(row.DictCode);
            $("#addEditDictName").val(row.DictName);
            $("#addEditDictValue").val(row.DictValue);
            $("#addEditIsActive").val(row.IsActive);
            $("#addEditParentCode").val(row.ParentCode);
            $("#addEditRemarks").val(row.Remarks);
            $("#addEditModal").modal('show');
        }

        $("#btnDelete").click(function () {
            var selections = $('#dataInfos').bootstrapTable('getSelections');
            if (selections.length < 1) {
                alert("请选择要删除的节点！");
                return;
            }
            if (!confirm("请确认删除！")) return;
            var codes = "";
            for (var i = 0; i < selections.length; i++) {
                codes += selections[i].DictCode + ",";
            }
            if (codes.endsWith(",")) {
                codes = codes.substr(0, codes.length - 1);
            }
            $.ajax({
                type: "post",
                url: "/Sys/Sys_Dictionary/Delete",
                data: "deleteCodes=" + codes,
                dataType: "json",
                success: function (data) {
                    if (data.Success) {
                        alert(data.Message);
                        $("button[name='refresh']").click();
                    } else {
                        alert(data.Message);
                    }
                },
                error: function (err) { }
            });
        });
    </script>
    <script>
        /**
         * 选中父项时，同时选中子项
         * param datas 所有的数据
         * param row 当前数据
         * param id id 字段名
         * param pid 父id字段名
         */
        function selectChilds(datas, row, id, pid, checked) {
            for (var i in datas) {
                if (datas[i][pid] == row[id]) {
                    datas[i].check = checked;
                    selectChilds(datas, datas[i], id, pid, checked);
                };
            }
        }

        function selectParentChecked(datas, row, id, pid) {
            for (var i in datas) {
                if (datas[i][id] == row[pid]) {
                    datas[i].check = true;
                    selectParentChecked(datas, datas[i], id, pid);
                };
            }
        }
    </script>
}